﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

namespace MyShop
{
    
    public partial class EditOrder : System.Web.UI.Page
    {

        public class OrderedStatusObj
        {
            public string ID { get; set; }
            public string Status { get; set; }
        }
        public List<OrderedStatusObj> DataOrderedStatus { get; set; }

        public class OrderedProductObj
        {
            public string OrderID { get; set; }
            public string NameProduct { get; set; }
            public string Count { get; set; }
            public string NeedCount { get; set; }
            public string Price { get; set; }
        }
        public List<OrderedProductObj> DataOrderedProduct { get; set; }

        public class OrderedUsersObj
        {
            public string ID { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Email { get; set; }
            public string Phone { get; set; }
            public string Delivery { get; set; }
            public string DateOrder { get; set; }
            public string Status { get; set; }
        }
        public List<OrderedUsersObj> DataOrderedUser { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                
            }
            

            List<OrderedStatusObj> mainResult = new List<OrderedStatusObj>();
            foreach (DataRow item in GetDataSet().Tables[1].Rows)
            {
                mainResult.Add(new OrderedStatusObj
                {
                    ID = item["ID"].ToString(),
                    Status = item["Name"].ToString()
                });
            }
            DataOrderedStatus = mainResult;


            GetDataProduct(GetDataSet().Tables[0]);


            

            //foreach (var row in GetDataSet().Tables[0].Rows)
            //{
            //     OrderedStatusObj obj = new OrderedStatusObj();
            //    obj.ID = row["ID"].
            //}
        }

       public void GetDataOrder(DataTable prod)
        {
            List<OrderedProductObj> mainResult = new List<OrderedProductObj>();
            foreach (DataRow item in prod.Rows)
            {
                mainResult.Add(new OrderedProductObj
                {
                    OrderID = item["OrderId"].ToString(),
                    Count = item["Count"].ToString(),
                    NeedCount = item["NeedCount"].ToString(),
                    NameProduct = item["Name"].ToString() + " - " +  item["CompanyName"].ToString() + " - " + item["ModelName"].ToString() ,
                    Price = item["Price"].ToString()
                });
            }
            DataOrderedProduct = mainResult;
            
                BindOrder();
        }

       public void BindOrder()
        {
            GridViewInfoOrder.DataSource = DataOrderedProduct;
            GridViewInfoOrder.DataBind();
        }

        private DataSet GetDataSet()
        {
            DataSet dataSet = new DataSet();
            using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
            {
                SqlCommand com = new SqlCommand("SELECT * FROM OrderedUsers SELECT * FROM OrderedStatus", sqlcon);
                DataTable dataTable = new DataTable();
                SqlDataAdapter dataAdapter = new SqlDataAdapter();
                
                dataAdapter.SelectCommand = com;
                dataAdapter.Fill(dataTable);
                dataSet.Tables.Add(dataTable);
                //GetDataProduct(dataTable);
            }

            using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
            {
                SqlCommand com = new SqlCommand("SELECT * FROM OrderedStatus", sqlcon);
                DataTable dataTable = new DataTable();
                SqlDataAdapter dataAdapter = new SqlDataAdapter();
                dataAdapter.SelectCommand = com;
                dataAdapter.Fill(dataTable);
                dataSet.Tables.Add(dataTable);
                //GetDataProduct(dataTable);
            }

            return dataSet;

        }

        public void GetDataProduct(DataTable prod)
        {
            List<OrderedUsersObj> mainResult = new List<OrderedUsersObj>();
            foreach (DataRow item in prod.Rows)
            {
                mainResult.Add(new OrderedUsersObj
                {
                    ID = item["ID"].ToString(),
                    FirstName = item["FirstName"].ToString(),
                    LastName = item["LastName"].ToString(),
                    Email = item["Email"].ToString(),
                    Phone = item["Phone"].ToString(),
                    Delivery = item["Delivery"].ToString(),
                    DateOrder = item["DateOrder"].ToString(),
                    Status = item["StatusOrder"].ToString()
                });
            }
            DataOrderedUser = mainResult;
            if (!IsPostBack)
            {
                BindProduct();

            }
        }

        public void BindProduct()
        {
            GridViewOrder.DataSource = DataOrderedUser;
            GridViewOrder.DataBind();
        }

        public void AllInfo_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;
            Session["OrderId"] = button.CommandArgument;

            if (Session["OrderId"] != null)
            {
                var orderID = (string)Session["OrderId"];
                DataSet dataSet = new DataSet();
                using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
                {
                    SqlCommand com = new SqlCommand("SELECT op.OrderId, op.Count as NeedCount, p.Price, p.ModelName, p.Count , p.Count, p.Price, pc.Name as CompanyName, pg.Name  FROM OrderedProduct op inner join Product p on op.ProductId = p.Id inner join ProductCompany pc on p.CompanyID = pc.ID inner join ProductGroup pg on p.GroupID = pg.ID where op.OrderId = " + orderID, sqlcon);
                    DataTable dataTable = new DataTable();
                    SqlDataAdapter dataAdapter = new SqlDataAdapter();

                    dataAdapter.SelectCommand = com;
                    dataAdapter.Fill(dataTable);
                    dataSet.Tables.Add(dataTable);
                    GetDataOrder(dataTable);
                }
            }
        }


        protected void ddlTest_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddl = sender as DropDownList;
            foreach (GridViewRow row in GridViewOrder.Rows)
            {
                Control ctrl = row.FindControl("StatusDropDownList") as DropDownList;
                if (ctrl != null)
                {
                    DropDownList ddl1 = (DropDownList)ctrl;
                    if (ddl.ClientID == ddl1.ClientID)
                    {
                        var id = row.Cells[0].Text;
                        var idStatus = ddl1.SelectedValue;
                        SaveChangedStatus(id, idStatus);
                        break;
                    }
                }
            }
        }

        private void SaveChangedStatus(string idOrder, string value)
        {
            using (SqlConnection sqlcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ShopConnectionString"].ConnectionString))
            {
                //SqlCommand com = new SqlCommand("SELECT * FROM OrderedStatus", sqlcon);
                DataTable dataTable = new DataTable();
                SqlDataAdapter dataAdapter = new SqlDataAdapter();
                dataAdapter.UpdateCommand = new SqlCommand("UPDATE OrderedUsers SET StatusOrder = @StatusOrder WHERE Id = @ID", sqlcon);
                dataAdapter.UpdateCommand.Parameters.Add("@StatusOrder", SqlDbType.Int).Value = Convert.ToInt32(value);
                dataAdapter.UpdateCommand.Parameters.Add("@ID", SqlDbType.Int).Value = Convert.ToInt32(idOrder);
                sqlcon.Open();
                dataAdapter.UpdateCommand.ExecuteNonQuery();
                sqlcon.Close();
            }
            
        }

        protected void GridViewOrder_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            DataTable myTable = new DataTable();

            DataColumn statusIDColumn = new DataColumn("ID");

            DataColumn statusNameColumn = new DataColumn("StatusName");

            myTable.Columns.Add(statusIDColumn);

            myTable.Columns.Add(statusNameColumn);

            DataSet ds = new DataSet();

            ds = GetDataSet();

            //int categoryID = 0;

            //string expression = String.Empty;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DropDownList ddl = (DropDownList)e.Row.FindControl("StatusDropDownList");
                DataTable table = ds.Tables[1];
                foreach (DataRow row in table.Rows)
                {

                    DataRow newRow = myTable.NewRow();

                    newRow["ID"] = row["ID"];

                    newRow["StatusName"] = row["Name"];

                    myTable.Rows.Add(newRow);

                }

                // ddl.DataSource = myTable;
                ddl.DataSource = DataOrderedStatus;

                ddl.DataTextField = "Status";

                ddl.DataValueField = "ID";

                ddl.DataBind();
                var curId = e.Row.Cells[0].Text;
                //ddl.SelectedValue = (e.Row.Cells[9].Text);
                ddl.SelectedValue = DataOrderedUser.First(d => d.ID == curId).Status;

            }
        }
        public override void VerifyRenderingInServerForm(Control control)
        {
        }
        protected void ButtonPrint_OnClick(object sender, EventArgs e)
        {

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=MARGEmployees.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            HtmlForm frm = new HtmlForm();
            GridViewInfoOrder.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(GridViewInfoOrder);
            frm.RenderControl(hw);
            GridViewInfoOrder.HeaderRow.Style.Add("width", "15%");
            GridViewInfoOrder.HeaderRow.Style.Add("font-size", "10px");
            GridViewInfoOrder.Style.Add("font-family", "Tahoma");
            GridViewInfoOrder.Style.Add("font-size", "8px");
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();

            //GridViewInfoOrder.PagerSettings.Visible = false;
            //GridViewInfoOrder.DataBind();
            //StringWriter sw = new StringWriter();
            //HtmlTextWriter hw = new HtmlTextWriter(sw);
            //GridViewInfoOrder.RenderControl(hw);
            //string gridHTML = sw.ToString().Replace("\"", "'")
            //    .Replace(System.Environment.NewLine, "");
            //StringBuilder sb = new StringBuilder();
            //sb.Append("<script type = 'text/javascript'>");
            //sb.Append("window.onload = new function(){");
            //sb.Append("var printWin = window.open('', '', 'left=0");
            //sb.Append(",top=0,width=1000,height=600,status=0');");
            //sb.Append("printWin.document.write(\"");
            //sb.Append(gridHTML);
            //sb.Append("\");");
            //sb.Append("printWin.document.close();");
            //sb.Append("printWin.focus();");
            //sb.Append("printWin.print();");
            //sb.Append("printWin.close();};");
            //sb.Append("</script>");
            //ClientScript.RegisterStartupScript(this.GetType(), "GridPrint", sb.ToString());
            //GridViewInfoOrder.PagerSettings.Visible = true;
            //GridViewInfoOrder.DataBind();
        }
    }
}